import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
sys.path.append(os.path.dirname(__file__))
import time
from datetime import datetime, date,timedelta
import re

import tushare as ts
from get_data import target_url
import json
from conf import setting
import functools

global pro  #在使用前初次声明
ts.set_token(setting.tushare_token)
pro = ts.pro_api()
#re前缀
def re_szshcode(code:str)->str:
    """
    对code增加前缀sh sz
    :param code:
    :return:
    """
    if re.match(r'^6.*',code):
        re_code='SH'+code
    if re.match(r'^(0|3).*',code):
        re_code='SZ'+code
    return re_code #SH600000,SZ000001
def dfcf_shszcode(code:str,time_var:str)->dict:
    """"dfcf_shszcode("000001")
    {'now实时': {'url': 'https://emappdata.eastmoney.com/stockrank/getCurrentList', 'headers': {}, 'params': {'appId': 'appId01', 'globalId': '786e4c21-70dc-435a-93bb-39', 'srcSecurityCode': 'SZ000001'}}}

    """
    shszcode=re_szshcode(code)
    target_url.dfcf_rank["{}".format(time_var)]['params']['srcSecurityCode'] = shszcode
    dict_=target_url.dfcf_rank
    return dict_

#class time
def time_start(days=20):
    """今天时间today_time 格式20200307
    开始时间start_time 格式20191108"""
    today_time = str(datetime.now())[:11]  # 2020-10-30 14:08:54.158185 ----->2020-10-30
    start_time = str(datetime.now() - timedelta(days))[:11]  # 2020-10-10 14:10:33.700162
    today_time = re.sub(r'\D', "", today_time)  # 20201030
    start_time = re.sub(r'\D', "", start_time)  # 20201010

    # ('20200731', '20200820', '16:12')
    return start_time, today_time, str(datetime.now())[11:16]

def time_saveandget(choose="one_day",day=13):#choose控制输出
    #time_saveandget().tolist()[-1]
    start_time,today_time,today_hour=time_start(day)
    trade_cal=pro.trade_cal(exchange='', start_date=start_time, end_date=today_time)
    i_num=-day+5
    trade_cal=trade_cal[trade_cal.is_open==1][i_num:].cal_date
    if choose=="one_day":
        return trade_cal.tolist()[-1]
    if choose=="day_list":
        return trade_cal.tolist()
"""4     20210825
5     20210826
6     20210827
9     20210830
10    20210831
11    20210901
12    20210902
13    20210903"""
def time_passed_9_30():
    """
    time_now:现在时间
    time_passed_9_30_with0：现在时间减去开盘时间，即为更新时间
    :return:大于9点30即为0
    """
    time_now=time.localtime(time.time())
    time_passed_9_30_with0=time_now.tm_hour-9.5+time_now.tm_min/60
    return time_passed_9_30_with0
#SAVE
def save(pandas:dict,time:str,name:str):#name=dfcf /ths

    path = os.path.join(setting.TOP100_DATA_PATH, '{}_{}.json'.format(time,name))
    pandas.to_csv("{}".format(path),encoding="utf-8")
def save_path(pandas:dict,time:str,path_var:str):#path

    path = os.path.join(setting.TOP100_DATA_PATH, '{}_{}.json'.format(time,name))
    pandas.to_csv("{}".format(path),encoding="utf-8")

#字典不等长pd.DataFrame(dict([(k, pd.Series(v)) for k, v in d.items()]))


#rq_________________________

if __name__ == '__main__':
    dfcf_shszcode("000001","his历史")
    print(time_saveandget("day_list"))
    print(time_saveandget())